<script setup lang="ts" name="InfraCronJob">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { dateTimeFormatter } from '@/utils/dateUtil'
import { dataToFile } from '@/components/Excel/src/helper'
import { CronJobApi, CronJobType } from '@/api/infra/cronJob'
import CronJobForm from './CronJobForm.vue'
import CronJobDetail from './CronJobDetail.vue'
import { checkPermit, computedOperateWidth } from '@/utils/permit'
import { getIntDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/enums/dictEnums'
import { InfraCronJobStatusEnum } from '@/enums/infraEnums'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const message = useMessage() // 消息弹窗
const { push } = useRouter() // 路由
const { t } = useI18n() // 国际化
const total = ref(0) // 列表的总页数
const list = ref([]) // 表格数据
const queryLoading = ref(false) // 列表加载中：1）列表数据加载；2）查询按钮禁用；3）重置按钮禁用
const queryParams = ref({
  pageIndex: 1,
  pageSize: 20,
  name: undefined,
  status: undefined,
  handlerName: undefined
})
const queryFormRef = ref() // 搜索的表单


/** 查询列表 */
const getList = async () => {
  queryLoading.value = true
  try {
    const data = await CronJobApi.page(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    queryLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageIndex = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.pageIndex = 1
  queryParams.value.pageSize = 20
  queryParams.value.name = undefined
  queryParams.value.status = undefined
  queryParams.value.handlerName = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 修改状态操作 */
const handleChangeStatus = async (row: CronJobType) => {
  try {
    // 修改状态的二次确认
    const text = row.status === InfraCronJobStatusEnum.STOP ? t('action', 'on') : t('action', 'pause')
    await message.confirm(
      t('infra.cronJob.message.updateStatus', 'confirm', [text, row.id]),
      t('message', 'reminder')
    )
    const status =
      row.status === InfraCronJobStatusEnum.STOP ? InfraCronJobStatusEnum.NORMAL : InfraCronJobStatusEnum.STOP
    await CronJobApi.updateStatus(row.id!, status)
    message.success(t('infra.cronJob.message.updateStatus', 'success', [text]))
    // 刷新列表
    await getList()
  } catch { }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CronJobApi.delete(id)
    message.success(t('message.del', 'success'))
    // 刷新列表
    await getList()
  } catch { }
}

/** '更多'操作按钮 */
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleRun':
      handleRun(row)
      break
    case 'openDetail':
      openDetail(row.id)
      break
    case 'handleJobLog':
      handleCronJobLog(row?.id)
      break
    default:
      break
  }
}

/** 执行一次 */
const handleRun = async (row: CronJobType) => {
  try {
    // 二次确认
    await message.confirm(t('infra.cronJob.message.run', 'confirm', [row.name]), t('message', 'reminder'))
    // 提交执行
    await CronJobApi.run(row.id!)
    message.success(t('infra.cronJob.message.run', 'success'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 查看操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 跳转执行日志 */
const handleCronJobLog = (id?: number) => {
  if (id && id > 0) {
    push('/Infra/CronJob/Log?id=' + id)
  } else {
    push('/Infra/CronJob/Log')
  }
}

const ExcelExportDialogRef = ref()

const filedList = ref([
  { key: 'id', value: 'ID' },
  { key: 'name', value: t('infra.cronJob', 'name') },
  { key: 'status', value: t('infra.cronJob', 'status') },
  { key: 'handlerName', value: t('infra.cronJob', 'handlerName') },
  { key: 'handlerParam', value: t('infra.cronJob', 'handlerParam') },
  { key: 'cronExpression', value: t('infra.cronJob', 'cronExpression') },
  { key: 'retryCount', value: t('infra.cronJob', 'retryCount') },
  { key: 'retryInterval', value: t('infra.cronJob', 'retryInterval') },
  { key: 'monitorTimeout', value: t('infra.cronJob', 'monitorTimeout') },
  { key: 'create_time', value: t('common', 'createTime') },
  { key: 'remark', value: t('common', 'remark') }
])
/** 导出按钮操作 */
const handleExport = async () => {
  ExcelExportDialogRef.value.open()
}

const exportDone = async (res) => {
  if (res.dataScope === 1) {
    dataToFile(list.value, res)
  } else if (res.dataScope === 3) {
    const allList = await CronJobApi.export(queryParams.value)
    dataToFile(allList, res)
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<template>
  <PageCard>
    <ContentFormTable>
      <template #header>
        <ElForm ref="queryFormRef" :model="queryParams" :inline="true">
          <ElFormItem :label="t('infra.cronJob', 'name')" prop="name" class="!w-240px">
            <el-input v-model="queryParams.name" :placeholder="t('infra.cronJob.rules', 'name')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem :label="t('infra.cronJob', 'status')" prop="status">
            <el-select v-model="queryParams.status" class="!w-160px" clearable :placeholder="t('infra.cronJob.rules', 'status')" @change="handleQuery">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.INFRA_CRON_JOB_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </ElFormItem>
          <ElFormItem :label="t('infra.cronJob', 'handlerName')" prop="handlerName" class="!w-240px">
            <el-input v-model="queryParams.handlerName" :placeholder="t('infra.cronJob.rules', 'handlerName')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem>
            <el-button type="primary" :disabled="queryLoading" icon="Search" @click="handleQuery">{{ t('action',
              'search') }}</el-button>
            <el-button icon="Refresh" :disabled="queryLoading" @click="resetQuery">{{ t('action', 'reset')
            }}</el-button>
            <el-button v-if="checkPermit(['infra:cron-job:create'])" type="success" icon="Plus" @click="openForm('create')">{{ t('action', 'create') }}</el-button>
            <CButton v-if="checkPermit(['infra:cron-job:export'])" type="warning" :disabled="queryLoading" :onClick="handleExport" preIcon="ri:export-line" :title="t('action', 'export')" />
            <CButton v-if="checkPermit(['infra:cron-job-log:index'])" type="info" :disabled="queryLoading" :onClick="handleCronJobLog" preIcon="ri:equalizer-3-fill" :title="t('infra.cronJob.log', 'title')" />
          </ElFormItem>
        </ElForm>
      </template>
      <template #content>
        <el-table v-loading="queryLoading && systemConfig.loadingType === 'module'" :data="list" border>
          <el-table-column prop="id" :label="t('common', 'id')" align="center" />
          <el-table-column prop="name" :label="t('infra.cronJob', 'name')" align="center" />
          <el-table-column :label="t('infra.cronJob', 'status')" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.INFRA_CRON_JOB_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column prop="handlerName" :label="t('infra.cronJob', 'handlerName')" align="center" />
          <el-table-column prop="handlerParam" :label="t('infra.cronJob', 'handlerParam')" show-overflow-tooltip align="center" />
          <el-table-column prop="cronExpression" :label="t('infra.cronJob', 'cronExpression')" show-overflow-tooltip align="center" />
          <el-table-column prop="remark" :label="t('common', 'remark')" show-overflow-tooltip align="center" />
          <el-table-column prop="create_time" :label="t('common', 'createTime')" :formatter="dateTimeFormatter" align="center" />
          <el-table-column prop="operate" :label="t('common', 'operate')" :width="44 + computedOperateWidth(['infra:data-source-config:update', 'infra:data-source-config:delete']) + (checkPermit(['infra:cron-job:update-status']) ? 66 : 0)" align="center" fixed="right">
            <template #default="scope">
              <el-button v-if="checkPermit(['infra:cron-job:update'])" type="primary" icon="Edit" @click="openForm('update', scope.row.id)" />
              <el-button v-if="checkPermit(['infra:cron-job:delete'])" type="danger" icon="Delete" @click="handleDelete(scope.row.id)" />
              <el-button
                v-if="checkPermit(['infra:cron-job:update-status'])"
                link
                :type="scope.row.status === InfraCronJobStatusEnum.STOP ? 'success' : 'info'"
                :icon="scope.row.status === InfraCronJobStatusEnum.STOP ? 'VideoPlay' : 'VideoPause'"
                @click="handleChangeStatus(scope.row)"
                >{{ scope.row.status === InfraCronJobStatusEnum.STOP ? t('action', 'on') : t('action', 'pause') }}</el-button
              >
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button type="primary" link class="ml-12px"><SvgIcon icon="ri:more-fill" size="26" /></el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-if="checkPermit(['infra:cron-job:trigger'])" command="handleRun"> {{ t('infra.cronJob.action', 'run') }} </el-dropdown-item>
                    <el-dropdown-item command="openDetail"> {{ t('infra.cronJob.action', 'detail') }} </el-dropdown-item>
                    <el-dropdown-item v-if="checkPermit(['infra:cron-job-log:index'])" command="handleJobLog"> {{ t('infra.cronJob.log', 'title') }} </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageIndex" :total="total" :disabled="queryLoading" @pagination="getList" />
        <!-- 表单弹窗：添加/修改 -->
        <CronJobForm ref="formRef" @success="getList" />
        <!-- 表单弹窗：查看 -->
        <CronJobDetail ref="detailRef" />
        <!-- 表单弹窗：导出 -->
        <ExcelExportDialog ref="ExcelExportDialogRef" :filename="t('infra.cronJob', 'title')" :hasSelected="false" :fieldList="filedList" @success="exportDone" />
      </template>
    </ContentFormTable>
  </PageCard>
</template>

<style scoped lang="scss">
.el-table {
  width: 100%;
  height: 100%;
}
</style>
